package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.vo.ChatMessageStatisticsVO;
import com.zenithmind.chat.service.ChatMessageStatisticsService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息统计控制器 - 遵循单一职责原则
 * 只负责消息统计的HTTP接口处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/chat/message-statistics")
@RequiredArgsConstructor
@Validated
@Tag(name = "消息统计管理", description = "消息统计相关接口")
public class ChatMessageStatisticsController {

    private final ChatMessageStatisticsService chatMessageStatisticsService;

    @PostMapping("/create")
    @Operation(summary = "创建消息统计", description = "为消息创建统计记录")
    public Result<String> createMessageStatistics(
            @Parameter(description = "消息ID") @RequestParam @NotBlank String messageId,
            @Parameter(description = "群组ID") @RequestParam(required = false) String groupId) {
        String userId = UserContext.getUserId();
        String statisticsId = chatMessageStatisticsService.createMessageStatistics(messageId, userId, groupId);
        return Result.success(statisticsId);
    }

    @GetMapping("/message/{messageId}")
    @Operation(summary = "查询消息统计", description = "根据消息ID查询统计信息")
    public Result<ChatMessageStatisticsVO> getStatisticsByMessageId(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        ChatMessageStatisticsVO statistics = chatMessageStatisticsService.getStatisticsByMessageId(messageId);
        return Result.success(statistics);
    }

    @PostMapping("/message/{messageId}/like")
    @Operation(summary = "增加点赞数", description = "为消息增加点赞数")
    public Result<Boolean> incrementLikeCount(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        Boolean result = chatMessageStatisticsService.incrementLikeCount(messageId);
        return Result.success(result);
    }

    @DeleteMapping("/message/{messageId}/like")
    @Operation(summary = "减少点赞数", description = "为消息减少点赞数")
    public Result<Boolean> decrementLikeCount(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        Boolean result = chatMessageStatisticsService.decrementLikeCount(messageId);
        return Result.success(result);
    }

    @PostMapping("/message/{messageId}/reply")
    @Operation(summary = "增加回复数", description = "为消息增加回复数")
    public Result<Boolean> incrementReplyCount(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        Boolean result = chatMessageStatisticsService.incrementReplyCount(messageId);
        return Result.success(result);
    }

    @DeleteMapping("/message/{messageId}/reply")
    @Operation(summary = "减少回复数", description = "为消息减少回复数")
    public Result<Boolean> decrementReplyCount(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        Boolean result = chatMessageStatisticsService.decrementReplyCount(messageId);
        return Result.success(result);
    }

    @PostMapping("/message/{messageId}/forward")
    @Operation(summary = "增加转发数", description = "为消息增加转发数")
    public Result<Boolean> incrementForwardCount(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        Boolean result = chatMessageStatisticsService.incrementForwardCount(messageId);
        return Result.success(result);
    }

    @PostMapping("/message/{messageId}/read")
    @Operation(summary = "增加阅读数", description = "为消息增加阅读数")
    public Result<Boolean> incrementReadCount(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        Boolean result = chatMessageStatisticsService.incrementReadCount(messageId);
        return Result.success(result);
    }

    @PostMapping("/batch-read")
    @Operation(summary = "批量增加阅读数", description = "批量为多个消息增加阅读数")
    public Result<Boolean> batchIncrementReadCount(@RequestBody @NotEmpty List<String> messageIds) {
        Boolean result = chatMessageStatisticsService.batchIncrementReadCount(messageIds);
        return Result.success(result);
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "查询用户消息统计", description = "查询用户的消息统计信息")
    public Result<List<ChatMessageStatisticsVO>> getUserMessageStatistics(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        List<ChatMessageStatisticsVO> statistics = chatMessageStatisticsService.getUserMessageStatistics(userId, startTime, endTime);
        return Result.success(statistics);
    }

    @GetMapping("/group/{groupId}")
    @Operation(summary = "查询群组消息统计", description = "查询群组的消息统计信息")
    public Result<List<ChatMessageStatisticsVO>> getGroupMessageStatistics(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        List<ChatMessageStatisticsVO> statistics = chatMessageStatisticsService.getGroupMessageStatistics(groupId, startTime, endTime);
        return Result.success(statistics);
    }

    @GetMapping("/user/{userId}/count")
    @Operation(summary = "统计用户消息总数", description = "统计用户在指定时间段的消息总数")
    public Result<Long> countUserMessages(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Long count = chatMessageStatisticsService.countUserMessages(userId, startTime, endTime);
        return Result.success(count);
    }

    @GetMapping("/group/{groupId}/count")
    @Operation(summary = "统计群组消息总数", description = "统计群组在指定时间段的消息总数")
    public Result<Long> countGroupMessages(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Long count = chatMessageStatisticsService.countGroupMessages(groupId, startTime, endTime);
        return Result.success(count);
    }

    @GetMapping("/group/{groupId}/popular")
    @Operation(summary = "查询热门消息排行", description = "查询群组的热门消息排行榜")
    public Result<List<ChatMessageStatisticsVO>> getPopularMessages(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "排行类型") @RequestParam @NotBlank String rankType,
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        List<ChatMessageStatisticsVO> popularMessages = chatMessageStatisticsService.getPopularMessages(
                groupId, rankType, limit, startTime, endTime);
        return Result.success(popularMessages);
    }

    @GetMapping("/user/{userId}/activity")
    @Operation(summary = "查询用户活跃度统计", description = "查询用户的活跃度统计信息")
    public Result<Object> getUserActivityStatistics(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Object statistics = chatMessageStatisticsService.getUserActivityStatistics(userId, startTime, endTime);
        return Result.success(statistics);
    }

    @GetMapping("/group/{groupId}/activity")
    @Operation(summary = "查询群组活跃度统计", description = "查询群组的活跃度统计信息")
    public Result<Object> getGroupActivityStatistics(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Object statistics = chatMessageStatisticsService.getGroupActivityStatistics(groupId, startTime, endTime);
        return Result.success(statistics);
    }

    @GetMapping("/group/{groupId}/message-type-distribution")
    @Operation(summary = "查询消息类型分布", description = "查询群组的消息类型分布统计")
    public Result<Object> getMessageTypeDistribution(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Object distribution = chatMessageStatisticsService.getMessageTypeDistribution(groupId, startTime, endTime);
        return Result.success(distribution);
    }

    @GetMapping("/group/{groupId}/time-distribution")
    @Operation(summary = "查询消息时间分布", description = "查询群组的消息时间分布统计")
    public Result<Object> getMessageTimeDistribution(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "时间粒度") @RequestParam @NotBlank String granularity,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Object distribution = chatMessageStatisticsService.getMessageTimeDistribution(groupId, startTime, endTime, granularity);
        return Result.success(distribution);
    }

    @GetMapping("/user/{userId}/interaction")
    @Operation(summary = "查询用户互动统计", description = "查询用户的互动统计信息")
    public Result<Object> getUserInteractionStatistics(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Object statistics = chatMessageStatisticsService.getUserInteractionStatistics(userId, startTime, endTime);
        return Result.success(statistics);
    }

    @GetMapping("/group/{groupId}/member-activity-rank")
    @Operation(summary = "查询成员活跃排行", description = "查询群组成员的活跃度排行榜")
    public Result<List<Object>> getGroupMemberActivityRank(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "排行类型") @RequestParam @NotBlank String rankType,
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        List<Object> rank = chatMessageStatisticsService.getGroupMemberActivityRank(
                groupId, rankType, limit, startTime, endTime);
        return Result.success(rank);
    }

    @PostMapping("/generate-report")
    @Operation(summary = "生成统计报告", description = "生成消息统计报告")
    public Result<String> generateStatisticsReport(
            @Parameter(description = "报告类型") @RequestParam @NotBlank String reportType,
            @Parameter(description = "目标ID") @RequestParam @NotBlank String targetId,
            @Parameter(description = "报告格式") @RequestParam(defaultValue = "excel") String format,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        String reportPath = chatMessageStatisticsService.generateStatisticsReport(
                reportType, targetId, startTime, endTime, format);
        return Result.success(reportPath);
    }

    @PostMapping("/cleanup-expired")
    @Operation(summary = "清理过期统计数据", description = "清理过期的统计数据")
    public Result<Integer> cleanupExpiredStatistics(
            @Parameter(description = "保留天数") @RequestParam(defaultValue = "90") Integer retentionDays) {
        Integer cleanedCount = chatMessageStatisticsService.cleanupExpiredStatistics(retentionDays);
        return Result.success(cleanedCount);
    }

    @PostMapping("/message/{messageId}/recalculate")
    @Operation(summary = "重新计算统计数据", description = "重新计算指定消息的统计数据")
    public Result<Boolean> recalculateStatistics(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        Boolean result = chatMessageStatisticsService.recalculateStatistics(messageId);
        return Result.success(result);
    }

    @PostMapping("/batch-recalculate")
    @Operation(summary = "批量重新计算统计数据", description = "批量重新计算多个消息的统计数据")
    public Result<Boolean> batchRecalculateStatistics(@RequestBody @NotEmpty List<String> messageIds) {
        Boolean result = chatMessageStatisticsService.batchRecalculateStatistics(messageIds);
        return Result.success(result);
    }

    @GetMapping("/export")
    @Operation(summary = "导出统计数据", description = "导出统计数据为文件")
    public Result<String> exportStatistics(
            @Parameter(description = "导出类型") @RequestParam @NotBlank String exportType,
            @Parameter(description = "目标ID") @RequestParam @NotBlank String targetId,
            @Parameter(description = "导出格式") @RequestParam(defaultValue = "excel") String format,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        String exportPath = chatMessageStatisticsService.exportStatistics(
                exportType, targetId, startTime, endTime, format);
        return Result.success(exportPath);
    }

    @GetMapping("/realtime/{statisticsType}")
    @Operation(summary = "获取实时统计数据", description = "获取实时的统计数据")
    public Result<Object> getRealTimeStatistics(
            @Parameter(description = "统计类型") @PathVariable @NotBlank String statisticsType,
            @Parameter(description = "目标ID") @RequestParam @NotBlank String targetId) {
        Object statistics = chatMessageStatisticsService.getRealTimeStatistics(statisticsType, targetId);
        return Result.success(statistics);
    }
}
